package com.zgx.plus.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zgx.plus.common.constant.ComConstant;
import com.zgx.plus.common.utils.SecurityUtils;
import com.zgx.plus.system.api.pos.SysMenu;
import com.zgx.plus.system.api.pos.SysRole;
import com.zgx.plus.system.api.pos.SysRoleMenu;
import com.zgx.plus.system.api.pos.SysUserRole;
import com.zgx.plus.system.api.vos.MetaVo;
import com.zgx.plus.system.api.vos.RouterVo;
import com.zgx.plus.system.mapper.SysMenuMapper;
import com.zgx.plus.system.service.SysMenuService;
import com.zgx.plus.system.service.SysRoleMenuService;
import com.zgx.plus.system.service.SysRoleService;
import com.zgx.plus.system.service.SysUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Resource
    private SysRoleMenuService sysRoleMenuService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysRoleService sysRoleService;

    @Override
    public Set<String> selectMenuPermsByRoleId(Long roleId) {
        return CollUtil.newHashSet(this.baseMapper.selectMenuPermsByRoleId(roleId));
//
//  //过滤可用角色
//  List<Long> ids = sysRoleService.listObjs(Wrappers.lambdaQuery(SysRole.class).select(SysRole::getRoleId).eq(SysRole::getStatus, ComConstant.STATUS_NORMAL)
//    .in(SysRole::getRoleId, roleIds), item -> Long.parseLong(String.valueOf(item)));
//  //根据可用角色查菜单
//  List<Long> menuIds = sysRoleMenuService.listByIds(ids).stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
//  //根据可用菜单查权限
//  return this.listObjs(Wrappers.lambdaQuery(SysMenu.class).select(SysMenu::getPerms).eq(SysMenu::getStatus, ComConstant.STATUS_NORMAL)
//    .in(SysMenu::getMenuId, menuIds), item -> Objects.isNull(item) ? null :String.valueOf(item)).stream().filter(Objects::nonNull).collect(Collectors.toList());
    }

    @Override
    public List<String> selectMenuPermsByUserId(Long userId) {
        //根据用户查角色
        List<Long> roleIds = sysUserRoleService.listByIds(Collections.singletonList(userId)).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());

        //过滤可用角色
        List<Long> ids = sysRoleService.listObjs(Wrappers.lambdaQuery(SysRole.class).select(SysRole::getRoleId).eq(SysRole::getStatus, ComConstant.STATUS_NORMAL)
                .in(SysRole::getRoleId, roleIds), item -> Long.parseLong(String.valueOf(item)));
        //根据可用角色查菜单
        List<Long> menuIds = sysRoleMenuService.listByIds(ids).stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
        //根据可用菜单查权限
        return this.listObjs(Wrappers.lambdaQuery(SysMenu.class).select(SysMenu::getPerms).eq(SysMenu::getStatus, ComConstant.STATUS_NORMAL)
                .in(SysMenu::getMenuId, menuIds), item -> Objects.isNull(item) ? null : String.valueOf(item)).stream().filter(Objects::nonNull).collect(Collectors.toList());
    }

    @Override
    public List<SysMenu> selectMenuTreeByUserId(Long userId) {
        List<SysMenu> menus = null;
        if (SecurityUtils.isAdmin(userId)) {
            menus = this.getBaseMapper().selectMenuTreeAll();
        } else {
            menus = this.getBaseMapper().selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

    @Override
    public List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), Objects.equals(1, menu.getIsCache()), menu.getPath()));
            List<SysMenu> cMenus = menu.getChildren();
            if (CollUtil.isNotEmpty(cMenus) && ComConstant.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), Objects.equals(1, menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(ComConstant.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    private List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) {
        //根据传入的某个父节点ID,遍历该父节点的所有子节点
        return list.stream().filter(item -> (item.getParentId() == parentId)).peek(item -> recursionFn(list, item)).collect(Collectors.toList());
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t    子节点
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        return list.stream().filter(item -> (item.getParentId().longValue() == t.getMenuId().longValue())).collect(Collectors.toList());
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    private String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{ComConstant.HTTP, ComConstant.HTTPS, ComConstant.WWW, "."},
                new String[]{"", "", "", "/"});
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (Objects.equals(0, menu.getParentId().intValue()) && StrUtil.equals(ComConstant.TYPE_DIR, menu.getMenuType())
                && Objects.equals(ComConstant.NO_FRAME, menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu) {
        String component = ComConstant.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = ComConstant.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = ComConstant.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenu menu) {
        return menu.getParentId().intValue() == 0 && ComConstant.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(ComConstant.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenu menu) {
        return menu.getIsFrame().equals(ComConstant.NO_FRAME) && (HttpUtil.isHttp(menu.getPath()) || HttpUtil.isHttps(menu.getPath()));
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu) {
        return menu.getParentId().intValue() != 0 && ComConstant.TYPE_DIR.equals(menu.getMenuType());
    }

}


